package com.weijing.pretty_app.util

import android.widget.TextView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

class LoadingAnimationHelper(private val loadingTextView: TextView) {
    private var animationJob: Job? = null

    /**
     * 开始加载动画（点从0到4循环）
     * @param baseText 基础文本，默认"Loading"
     * @param speed 动画速度（毫秒），默认500ms
     */
    fun startLoading(baseText: String = "Recovering", speed: Long = 500) {
        stopLoading() // 先停止之前的动画
        var dotCount = 0

        animationJob = CoroutineScope(Dispatchers.Main).launch {
            while (isActive) {
                val dots = ".".repeat(dotCount)
                loadingTextView.text = "$baseText$dots"
                dotCount = (dotCount + 1) % 5 // 0→1→2→3→4→0→...
                delay(speed)
            }
        }
    }

    /** 停止动画（可设置最终显示的文本） */
    fun stopLoading(finalText: String? = null) {
        animationJob?.cancel()
        finalText?.let { loadingTextView.text = it }
    }
}